<template>
  <div class="panel-box">
    <el-container>
      <el-aside v-if="leftVisible" :width="`${leftWidth}px`">
        <div class="top-bar">
          启用：{{ allQysl }}/{{ allZsl }}
          <div class="right">
            <el-button type="primary" @click="editGzfl()">新增</el-button>
          </div>
        </div>
        <div class="inner-box">
          <el-input v-model="gzflFilterGjz" placeholder="规则分类名称/规则分类标识" suffix-icon="el-icon-search"></el-input>
          <div class="gzfl-list-box" style="margin-top: 10px">
            <div v-for="item in gzflList"
                 v-show="item.gzflbs.indexOf(gzflFilterGjz)>-1||item.gzflmc.indexOf(gzflFilterGjz)>-1"
                 :key="item.gzflbm" :class="{active:currGzfl.gzflbm===item.gzflbm}"
                 class="list-item" @click="queryGzdyListByGzfl(item)">
              <div class="mc-box">
                <div :title="`${item.gzflmc}(${item.qysl}/${item.zsl})`">
                  {{ `${item.gzflmc}(${item.qysl}/${item.zsl})` }}
                </div>
                <div :title="item.gzflbs" style="font-size: 12px;color:red;">{{ item.gzflbs }}</div>
              </div>
              <div class="btn-box" @click.stop="{}">
                <div class="btn edit-btn" title="编辑" @click="editGzfl(item)"></div>
                <div class="btn delete-btn" title="删除"
                     @click="preDel(delGzfl,item,`即将删除【${item.gzflmc}】,删除后不可恢复，是否继续？`)"></div>
              </div>
            </div>
          </div>
        </div>
      </el-aside>
      <el-divider class="hidden-divider canhidden"
                  direction="vertical" @mousedown="handleDividerClick"/>
      <el-main class="noPadding">
        <div class="top-bar">
          <div style="margin-right: 10px">{{ `${currGzfl.gzflmc}(${currGzfl.qysl}/${currGzfl.zsl})` }}</div>
          <el-checkbox v-model="sfzkzj">只看自己</el-checkbox>
          <span style="margin: 0 20px">是否启用</span>
          <el-radio-group v-model="sfqy">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button label="Y">启用</el-radio-button>
            <el-radio-button label="N">未启用</el-radio-button>
          </el-radio-group>
          <el-button v-show="selectedCount" type="danger" @click="deleteSelectedGz">批量删除</el-button>
          <el-button v-show="selectedCount" type="primary" @click="copySelectedGz">批量复制</el-button>
          <div class="right">
            <el-button type="primary" @click="gzinfos=[];searchGzVisible=true">规则检索</el-button>
            <el-button type="primary" @click="importGzVisible=true">导入</el-button>
            <el-button type="primary" @click="editGzdy()">新增</el-button>
            <el-button type="primary" @click="startPx()">排序</el-button>
          </div>
        </div>
        <el-table
            ref="gzTable"
            :data="gzdyList"
            height="calc(100% - 30px)"
            row-key="gzbm"
            stripe
            style="width: 100%"
            @selection-change="handleGzdyListSelectionChange">
          <el-table-column
              type="selection"
              width="50">
          </el-table-column>
          <el-table-column
              label="序号"
              type="index"
              width="50">
          </el-table-column>
          <el-table-column
              v-if="zsItem.mc"
              :label="zsItem.mc"
              show-tooltip-when-overflow width="100">
            <template slot-scope="{row}">
              {{ getZsValue(row.gzpz) }}
            </template>
          </el-table-column>
          <el-table-column
              label="规则名称"
              show-tooltip-when-overflow>
            <template slot-scope="{row}">
              <el-link type="primary" @click="designGz(row)">{{ row.gzmc }}</el-link>
            </template>
          </el-table-column>
          <el-table-column
              label="规则描述"
              prop="gzms"
              show-overflow-tooltip>
          </el-table-column>
          <el-table-column
              label="创建人"
              prop="cjrymc"
              show-overflow-tooltip
              width="80">
          </el-table-column>
          <el-table-column
              label="规则编码"
              prop="gzbm"
              width="270">
          </el-table-column>
          <el-table-column
              align="center"
              label="启用"
              prop="sfqy"
              sortable
              width="85">
            <template slot-scope="{row}">
              <el-checkbox :value=" row.sfqy === 'Y'" @change="setGzdyQyzt(row)"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column
              label="创建时间"
              prop="cjsj"
              sortable
              width="180">
          </el-table-column>
          <el-table-column
              label="操作"
              width="140px">
            <template slot-scope="{row}">
              <!--<el-popover-->
              <!--    placement="top-start"-->
              <!--    width="210"-->
              <!--    trigger="hover">-->
              <!--  <template>-->
              <el-link type="primary" @click="copyGz(row)">复制</el-link>
              <el-link style="margin-left: 15px" type="primary" @click="editGzdy(row)">编辑</el-link>
              <el-link style="margin-left: 15px" type="danger"
                       @click="preDel(delGzdy,row,`即将删除【${row.gzmc}】,删除后不可恢复，是否继续？`)">删除
              </el-link>
              <!--  </template>-->
              <!--  <el-button slot="reference">操作</el-button>-->
              <!--</el-popover>-->
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>

    <xj-dialog :visible="searchGzVisible"
               height="80%"
               show-close
               title="规则检索" width="80%" @close="searchGzVisible=false">
      <div class="search-inputbox">
        <div class="search-input">
          <div class="search-item">
            <div class="label">规则名称</div>
            <el-input v-model="searchOpt.gzmc" clearable @keypress.native.enter="queryGzinfoListByGjz"/>
          </div>
          <div class="search-item">
            <div class="label">规则描述</div>
            <el-input v-model="searchOpt.gzms" clearable @keypress.native.enter="queryGzinfoListByGjz"/>
          </div>
          <div class="search-item">
            <div class="label">规则编码</div>
            <el-input v-model="searchOpt.gzbm" clearable @keypress.native.enter="queryGzinfoListByGjz"/>
          </div>
          <div v-if="zsItem.bm" class="search-item">
            <div class="label">{{ zsItem.mc }}</div>
            <div v-show="zsItem.lx!=='input'">
              <el-select v-model="searchOpt.gzpz" clearable @keypress.native.enter="queryGzinfoListByGjz">
                <el-option
                    v-for="item in  zsItem.options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </div>
            <div v-show="zsItem.lx==='input'">
              <el-input v-model="searchOpt.gzpz" clearable @keypress.native.enter="queryGzinfoListByGjz"></el-input>
            </div>
          </div>
        </div>
        <el-button type="primary" @click="queryGzinfoListByGjz">检索</el-button>
      </div>
      <el-table :data="gzinfos" height="calc(100% - 47px)">
        <el-table-column align="center" label="序号" type="index" width="50px"></el-table-column>
        <el-table-column v-if="zsItem.mc"
                         :label="zsItem.mc" show-tooltip-when-overflow width="100">
          <template slot-scope="{row}">
            <span v-html="highlight(getZsValue(row.gzpz), searchOpt.gzpz)"></span>
          </template>
        </el-table-column>
        <el-table-column label="规则名称"
                         property="gzmc" show-tooltip-when-overflow>
          <template v-slot="{row}">
            <el-link type="primary" @click="designGz(row)">
              <span v-html="highlight(row.gzmc, searchOpt.gzmc)"></span>
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="规则分类名称"
                         property="gzflmc" show-tooltip-when-overflow></el-table-column>
        <el-table-column label="规则描述" property="gzms" show-tooltip-when-overflow>
          <template v-slot="{row}">
            <span v-html="highlight(row.gzms, searchOpt.gzms)"></span>
          </template>
        </el-table-column>
        <el-table-column label="规则编码" property="gzbm" width="270">
          <template v-slot="{row}">
            <span v-html="highlight(row.gzbm, searchOpt.gzbm)"></span>
          </template>
        </el-table-column>
        <el-table-column
            align="center"
            label="启用"
            prop="sfqy"
            sortable
            width="80">
          <template slot-scope="{row}">
            <el-checkbox :value=" row.sfqy === 'Y'" @change="setGzdyQyzt(row)"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            width="140px">
          <template slot-scope="{row}">
            <el-link type="primary" @click="jumpToGz(row.gzflbm,row.gzbm)">定位</el-link>
            <el-link style="margin-left: 15px" type="primary" @click="editGzdy(row)">编辑</el-link>
            <el-link style="margin-left: 15px" type="danger"
                     @click="preDel(delGzdy,row,`即将删除【${row.gzmc}】,删除后不可恢复，是否继续？`)">删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </xj-dialog>
    <xj-dialog :title="(gzflForm.gzflbm?'编辑':'新增')+'规则分类'"
               :visible="addGzflDialogVisible"
               height="100vh">
      <el-form :model="gzflForm" style="height:calc(100% - 18px)">
        <el-form-item v-show="!gzflForm.gzflbm" label="分类来源" label-width="120px">
          <el-radio-group v-model="gzflForm.gzflly">
            <el-radio-button label="0">自定义</el-radio-button>
            <el-radio-button label="sjmxTable">数据模型</el-radio-button>
            <el-radio-button label="ajmxTable">案件模型</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <div v-show="gzflForm.gzflly==='0'">
          <el-form-item label="规则分类名称" label-width="120px">
            <el-input v-model="gzflForm.gzflmc" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="规则分类标识" label-width="120px">
            <el-input v-model="gzflForm.gzflbs" autocomplete="off"></el-input>
          </el-form-item>
        </div>
        <div v-show="gzflForm.gzflly==='sjmxTable'" style="height:100%">
          <el-form-item label="关键字" label-width="120px">
            <el-input v-model="filterGjz" placeholder="规则分类名称/规则分类标识" suffix-icon="el-icon-search"></el-input>
          </el-form-item>
          <el-table
              ref="sjmxTable"
              :data="sjmxDataShow"
              height="calc(100% - 50px)"
              style="width: 100%">
            <el-table-column
                :selectable="isAddGzfl"
                type="selection"
                width="50">
            </el-table-column>
            <el-table-column
                label="序号"
                type="index"
                width="50">
            </el-table-column>
            <el-table-column
                label="规则分类名称"
                prop="gzflmc">
            </el-table-column>
            <el-table-column
                label="规则分类标识"
                prop="gzflbs"
                width="340">
            </el-table-column>
          </el-table>
        </div>
        <div v-show="gzflForm.gzflly==='ajmxTable'" style="height:100%">
          <el-form-item label="关键字" label-width="120px">
            <el-input v-model="filterGjz" placeholder="规则分类名称/规则分类标识" suffix-icon="el-icon-search"></el-input>
          </el-form-item>
          <el-table
              ref="ajmxTable"
              :data="ajmxDataShow"
              height="calc(100% - 50px)"
              style="width: 100%">
            <el-table-column
                :selectable="isAddGzfl"
                type="selection"
                width="50">
            </el-table-column>
            <el-table-column
                label="序号"
                type="index"
                width="50">
            </el-table-column>
            <el-table-column
                label="规则分类名称"
                prop="gzflmc">
            </el-table-column>
            <el-table-column
                label="规则分类标识"
                prop="gzflbs"
                width="340">
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleAddGzflBtnClick(false)">取消</el-button>
        <el-button type="primary" @click="handleAddGzflBtnClick(true)">确定</el-button>
      </div>
    </xj-dialog>
    <xj-dialog :visible="!!selectedGzbmList.length" title="选择规则分类">
      关键字：
      <el-input v-model="gzflTagFilterGjz" placeholder="规则分类名称" style="width: 300px;"></el-input>
      <div
          style="display:grid;grid-template-columns: repeat(auto-fit,150px);grid-gap: 10px;grid-column-gap: 10px;margin-top: 10px">
        <el-tag
            v-for="gzfl in gzflList"
            v-show="~gzfl.gzflmc.indexOf(gzflTagFilterGjz)"
            :key="gzfl.gzflbm"
            :effect="selectGzfl[gzfl.gzflbm]?'dark':'plain'"
            :title="gzfl.gzflmc"
            size="medium"
            style="user-select:none;text-align: center;text-overflow: ellipsis;overflow: hidden;white-space: nowrap;cursor: pointer"
            @click="toggleSelect(gzfl)">{{ gzfl.gzflmc }}
        </el-tag>
      </div>
      <template slot="footer">
        <el-button @click="handleCopyGzBtnClick(false)">取消</el-button>
        <el-button type="primary" @click="handleCopyGzBtnClick(true)">确定</el-button>
      </template>
    </xj-dialog>
    <xj-dialog :visible="pxVisible" title="规则排序" width="500px">
      <transition-group tag="div">
        <div v-for="(gzdy,idx) in pxGz"
             :key="gzdy.gzbm"
             :class="{
              over:overGzbm+pos===gzdy.gzbm+'over',
              'over-top':overGzbm+pos===gzdy.gzbm+'top',
              'over-bottom':overGzbm+pos===gzdy.gzbm+'bottom',
           }"
             class="list-item canmove"
             draggable
             @dragover="handleDragOver($event,gzdy)"
             @dragstart="handleDragStart($event,gzdy)"
             @drop="handleDrop($event,gzdy)">
          <span style="color: red;margin-right: 10px;flex-shrink: 0;">{{ gzdy.yssx + 1 }}</span>
          <span style="color: red;margin-right: 10px;flex-shrink: 0;font-family: Consolas,serif;">---></span>
          <span style="color: red;margin-right: 10px;flex-shrink: 0;">{{ idx + 1 }}</span>
          {{ gzdy.gzmc }}
        </div>
      </transition-group>
      <template slot="footer">
        <el-button @click="handlePxClick(false)">取消</el-button>
        <el-button type="primary" @click="handlePxClick(true)">确定</el-button>
      </template>
    </xj-dialog>
    <xj-dialog :visible="importGzVisible" title="请选择导入的规则">
      <el-cascader-panel v-model="selectedImportGzdyList" :props="props"></el-cascader-panel>
      <div slot="footer">
        <el-button @click="handleImportGzdyBtnClick(false)">取消</el-button>
        <el-button type="primary" @click="handleImportGzdyBtnClick(true)">确定</el-button>
      </div>
    </xj-dialog>
    <xj-dialog :title="(gzdyForm.gzbm?'编辑':'新增')+'规则定义'" :visible="editGzdyVisible">
      <el-form :model="gzdyForm" label-width="120px">
        <div class="form-box">
          <el-form-item label="规则名称">
            <el-input v-model="gzdyForm.gzmc"></el-input>
          </el-form-item>
          <!--<el-form-item label="规则描述">-->
          <!--  <el-input v-model="gzdyForm.gzms"></el-input>-->
          <!--</el-form-item>-->
          <el-form-item label="规则描述">
            <el-input v-model="gzdyForm.gzms" type="textarea"/>
          </el-form-item>

          <el-form-item v-for="item in xmItem.xmpz.items" :key="item.bm" :label="item.mc">
            <el-radio-group v-if="item.lx==='radio-button'" v-model="gzdyForm.gzpz[item.bm]">
              <el-radio-button v-for="_item in item.options" :key="_item.value" :label="_item.value">{{ _item.label }}
              </el-radio-button>
            </el-radio-group>
            <el-select v-if="item.lx==='select'" v-model="gzdyForm.gzpz[item.bm]" style="width: 100%">
              <el-option v-for="_item in item.options" :key="_item.value" :label="_item.label" :value="_item.value">
                {{ _item.label }}
              </el-option>
            </el-select>
            <el-input v-if="item.lx==='input'" v-model="gzdyForm.gzpz[item.bm]"></el-input>
          </el-form-item>

        </div>
      </el-form>
      <div slot="footer">
        <el-button @click="handleEditGzdyBtnClick(false)">取消</el-button>
        <el-button type="primary" @click="handleEditGzdyBtnClick(true)">确定</el-button>
      </div>
    </xj-dialog>
  </div>
</template>

<script>
import commonMixins from "@/mixins/commonMixins";
import XjDialog from "@/components/XjDialog";
import sjmxData from '../data/sjmxData.json'
import ajmxData from '../data/ajmxData.json'

export default {
  name: "Gzgl",
  components: { XjDialog },
  mixins: [commonMixins],
  data () {
    return {
      sfzkzj: false,
      sfqy: "",
      leftWidth: 300,
      leftVisible: true,
      sjmxData,
      ajmxData,
      gzflList: [],
      addGzflDialogVisible: false,
      importGzVisible: false,
      editGzdyVisible: false,
      gzflTagFilterGjz: '',
      gzflForm: {
        gzflbm: '',
        gzflmc: '',
        gzflbs: '',
        gzflly: '0'
      },
      gzdyForm: {
        gzbm: '',
        gzpz: {}
      },
      currGzfl: {
        qysl: 0,
        zsl: 0
      },
      gzdyList: [],
      selectedGzbmList: [],
      selectedImportGzdyList: [],
      props: {
        lazy: true,
        multiple: true,
        lazyLoad: async (node, resolve) => {
          const { level, value } = node;
          if (level === 0) {
            let xmList = await this.$api.queryXmListByRybm({ rybm: this.yhxx.rybm })
            resolve(xmList.filter(item => item.xmbm !== this.xmItem.xmbm).map(item => {
              return {
                label: item.xmmc,
                value: item.xmbm,
                leaf: false
              }
            }))
          } else if (level === 1) {
            // 加载规则分类
            let gzflList = await this.$api.queryGzflListByXmbm({ xmbm: value })
            resolve(gzflList.map(item => {
              return {
                label: item.gzflmc,
                value: item.gzflbm,
                leaf: false
              }
            }))
          } else if (level === 2) {
            // 加载规则定义
            let gzdyList = await this.$api.queryGzdyListByGzflbm({ gzflbm: value })
            resolve(gzdyList.map(item => {
              return {
                label: item.gzmc,
                value: item.gzbm,
                leaf: true
              }
            }))
          } else {
            resolve([])
          }
        },
      },

      pxGz: [],
      dragGzdy: null,
      overGzbm: '',
      pos: '',
      pxVisible: false,
      filterGjz: '',
      gzflFilterGjz: '',
      selectGzfl: {},
      selectedCount: 0,

      searchGzVisible: false,
      searchOpt: {
        gzmc: '',
        gzms: '',
        gzbm: '',
        gzpz: ''
      },
      gzinfos: [],
    }
  },
  computed: {
    allQysl () {
      return this.gzflList.reduce((re, item) => re + item.qysl, 0)
    },
    allZsl () {
      return this.gzflList.reduce((re, item) => re + item.zsl, 0)
    },
    sjmxDataShow () {
      return this.sjmxData.filter(item => {
        let b = item.mxbm.indexOf(this.filterGjz) > -1
        if (b) return true
        return item.mxmc.indexOf(this.filterGjz) > -1
      }).map(item => {
        return {
          gzflmc: item.mxmc,
          gzflbs: item.mxbm,
        }
      })
    },
    ajmxDataShow () {
      return this.ajmxData.filter(item => {
        let b = item.mxbm.indexOf(this.filterGjz) > -1
        if (b) return true
        return item.mxmc.indexOf(this.filterGjz) > -1
      }).map(item => {
        return {
          gzflmc: item.mxmc,
          gzflbs: item.mxbm,
        }
      })
    },
    zsItem () {
      let i = this.xmItem.xmpz.items.find(item => item.bm === this.xmItem.xmpz.zsbm)
      return i || {}
    }
  },
  async mounted () {
    let gzglSfzkzj = mySessionStorage.getItem("gzgl-sfzkzj", false)
    let gzglSfqy = mySessionStorage.getItem("gzgl-sfqy", "")
    this.sfzkzj = gzglSfzkzj
    this.sfqy = gzglSfqy
    await this.$store.dispatch("loadMxstgxList")
    this.queryGzflListByXmbm()
  },
  watch: {
    sfzkzj () {
      mySessionStorage.setItem("gzgl-sfzkzj", this.sfzkzj)
      this.queryGzdyList()
    },
    sfqy () {
      mySessionStorage.setItem("gzgl-sfqy", this.sfqy)
      this.queryGzdyList()
    }
  },
  methods: {
    handleDividerClick (ev) {
      // this.leftVisible = !this.leftVisible
      let oldWidth = this.leftWidth
      let oldX = ev.screenX
      const move = e => {
        this.leftWidth = oldWidth + e.screenX - oldX
      }
      const up = e => {

        window.removeEventListener("mousemove", move)
        window.removeEventListener("mouseup", up)
      }
      window.addEventListener("mousemove", move)
      window.addEventListener("mouseup", up)
    },
    highlight (str, word) {
      if (!str) return ""
      return str.replace(word, w => `<span style="color:red;">${w}</span>`)
    },
    async queryGzinfoListByGjz () {
      try {
        if (!this.searchOpt.gzmc && !this.searchOpt.gzms && !this.searchOpt.gzbm && !this.searchOpt.gzpz) {
          let zsmc = this.zsItem.bm ? `、${this.zsItem.mc}` : ''
          throw new Error(`规则名称、规则描述、规则编码${zsmc}不能全为空`)
        }
        this.gzinfos = await this.$api.queryGzinfoListByGjz({
          ...this.searchOpt,
          xmbm: this.xmItem.xmbm,
          gzpz: (this.zsItem.bm && this.searchOpt.gzpz) ? `"${this.zsItem.bm}":"%${this.searchOpt.gzpz}%"` : ''
        })
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    $tableScrollMove (refName, index = 0) {
      if (!refName || !this.$refs[refName]) return//不存在表格的ref vm 则返回
      let vmEl = this.$refs[refName].$el
      if (!vmEl) return
      //计算滚动条的位置
      let elementNodeListOfElement = vmEl.querySelectorAll('.el-table__body tr')[index];
      const targetTop = elementNodeListOfElement.getBoundingClientRect().top
      const containerTop = vmEl.querySelector('.el-table__body').getBoundingClientRect().top
      const scrollParent = vmEl.querySelector('.el-table__body-wrapper')
      scrollParent.scrollTop = targetTop - containerTop
      let tdList = elementNodeListOfElement.querySelectorAll("td")
      tdList.forEach(item => {
        item.style.backgroundColor = "rgba(64, 158, 255, 0.5)"
        setTimeout(() => {
          item.style.backgroundColor = "unset"
        }, 300)
      })
    },
    async jumpToGz (gzflbm, gzbm) {
      if (this.currGzfl.gzflbm !== gzflbm) {
        await this.queryGzdyListByGzfl({ gzflbm })
      }
      if (gzbm) {
        let idx = this.gzdyList.findIndex(r => r.gzbm === gzbm)
        this.$tableScrollMove("gzTable", idx)
      }
    },
    async handleEditGzdyBtnClick (isConfirm) {
      if (isConfirm) {
        let gzdy = {
          gzbm: this.gzdyForm.gzbm,
          gzmc: this.gzdyForm.gzmc,
          gzms: this.gzdyForm.gzms,
          gzflbm: this.gzdyForm.gzflbm,
          gzpz: JSON.stringify(this.gzdyForm.gzpz)
        }
        if (this.gzdyForm.gzbm) {
          try {
            await this.$api.updateGzdy(gzdy)
            this.$message({ message: "修改成功", type: 'success' })
          } catch (e) {
            this.$message({ message: e.message, type: 'error' })
            return
          }
        } else {
          try {
            await this.$api.addGzdy(gzdy)
            this.$message({ message: "添加成功", type: 'success' })
          } catch (e) {
            this.$message({ message: e.message, type: 'error' })
            return
          }
        }
        this.queryGzdyList()

        if (this.searchGzVisible) {
          this.queryGzinfoListByGjz()
        }
      }
      this.editGzdyVisible = false

    },
    async handleImportGzdyBtnClick (isConfirm) {
      if (isConfirm) {
        let errArr = []
        for (let selectedImportGzdyListElement of this.selectedImportGzdyList) {
          try {
            let gzbm = selectedImportGzdyListElement[2]
            await this.copyGzToGzfl(gzbm, this.currGzfl.gzflbm)
          } catch (e) {
            errArr.push(e.message)
          }
        }
        this.queryGzdyList()
        if (errArr.length) {
          this.$message({ message: `部分规则导入失败：${errArr.join(",")}`, type: 'warning' })
        } else {
          this.$message({ message: "导入成功", type: 'success' })
        }
      }
      this.importGzVisible = false
      this.selectedImportGzdyList = []
    },
    handleGzdyListSelectionChange (selection) {
      this.selectedCount = selection.length
    },
    toggleSelect (gzfl) {
      this.$set(this.selectGzfl, gzfl.gzflbm, !this.selectGzfl[gzfl.gzflbm])
    },
    isAddGzfl (row, idx) {
      return !this.gzflList.find(item => item.gzflbs === row.gzflbs)
    },
    startPx () {
      this.pxGz = this.gzdyList.map((item, idx) => ({ gzbm: item.gzbm, gzmc: item.gzmc, yssx: idx }))
      this.pxVisible = true
    },
    handleDragStart (e, gzdy) {
      this.dragGzdy = gzdy
    },
    handleDragOver (e, gzdy) {
      let el = e.target
      do {
        if (el.classList.contains('list-item')) break
      } while ((el = el.parentNode))
      let totalHeight = el.offsetHeight
      let y = e.offsetY
      this.overGzbm = gzdy.gzbm
      if (y <= totalHeight / 4) {
        this.pos = "top"
      } else if (y <= totalHeight * 3 / 4) {
        this.pos = "over"
      } else {
        this.pos = "bottom"
      }
      e.preventDefault()
    },
    handleDrop (e, gzdy) {
      if (this.dragGzdy.gzbm === gzdy.gzbm) {
        this.pos = ''
        return
      }
      let gzList = this.pxGz
      let oldIdx = gzList.findIndex(item => item.gzbm === this.dragGzdy.gzbm)
      if (oldIdx !== -1) {
        if (this.pos === 'top') {
          // 删除旧的
          let oldItem = gzList[oldIdx]
          gzList.splice(oldIdx, 1)
          // 插入到新位置
          let newIdx = gzList.findIndex(item => item.gzbm === gzdy.gzbm)
          gzList.splice(newIdx, 0, oldItem)
        } else if (this.pos === "over") {
          let oldItem = gzList[oldIdx]

          let newIdx = gzList.findIndex(item => item.gzbm === gzdy.gzbm)
          let newItem = gzList[newIdx]

          // 交换两个
          gzList.splice(oldIdx, 1, newItem)
          gzList.splice(newIdx, 1, oldItem)
        } else {
          // 删除旧的
          let oldItem = gzList[oldIdx]
          gzList.splice(oldIdx, 1)
          // 插入到新位置
          let newIdx = gzList.findIndex(item => item.gzbm === gzdy.gzbm)
          gzList.splice(newIdx + 1, 0, oldItem)
        }
      }
      this.pos = ''
    },
    async handlePxClick (isConfirm) {
      if (isConfirm) {
        try {
          let params = this.pxGz.map((item, idx) => ({ gzbm: item.gzbm, px: idx }))
          await this.$api.sortGzdy(params)
          this.queryGzdyList()
        } catch (e) {
          return this.$message({ message: e.message, type: 'error' })
        }
      }
      this.pxVisible = false
    },
    async queryGzflListByXmbm () {
      try {
        this.gzflList = await this.$api.queryGzflListByXmbm({ xmbm: this.xmItem.xmbm })
        if (!this.gzflList.length) return
        let gzflItem = mySessionStorage.getItem('gzfl-item', {})
        let gzfl = this.gzflList.find(item => item.gzflbm === gzflItem.gzflbm)
        if (gzfl == null) gzfl = this.gzflList[0]
        this.queryGzdyListByGzfl(gzfl)
      } catch (e) {
        this.$message({ message: e.message, type: 'error' })
      }
    },
    async delGzfl (gzfl) {
      try {
        await this.$api.deleteGzfl({ gzflbm: gzfl.gzflbm })
        this.queryGzflListByXmbm()
        this.handleAddGzflBtnClick(false)
      } catch (e) {
        this.$message({ message: e.message, type: 'error' })
      }
    },
    async handleAddGzflBtnClick (isConfirm) {
      if (isConfirm) {
        // 进行保存
        try {
          if (this.gzflForm.gzflbm) {
            await this.$api.updateGzfl({
              gzflbm: this.gzflForm.gzflbm,
              gzflbs: this.gzflForm.gzflbs,
              gzflmc: this.gzflForm.gzflmc
            })
          } else {
            if (this.gzflForm.gzflly === '0') {
              await this.$api.addGzfl({
                gzflbs: this.gzflForm.gzflbs,
                gzflmc: this.gzflForm.gzflmc,
                xmbm: this.xmItem.xmbm
              })
            } else {
              // 批量添加
              let table = this.$refs[this.gzflForm.gzflly]
              let selection = table.selection
              for (let selectionElement of selection) {
                await this.$api.addGzfl({
                  gzflbs: selectionElement.gzflbs,
                  gzflmc: selectionElement.gzflmc,
                  xmbm: this.xmItem.xmbm
                })
              }
            }
          }
          this.queryGzflListByXmbm()
        } catch (e) {
          this.$message({ message: e.message, type: 'error' })
          return
        }
      }
      this.addGzflDialogVisible = false
    },
    editGzfl (gzfl) {
      gzfl = gzfl || {}
      this.gzflForm = {
        gzflly: "0",
        gzflbm: gzfl.gzflbm, gzflmc: gzfl.gzflmc, gzflbs: gzfl.gzflbs
      }
      this.addGzflDialogVisible = true
    },
    queryGzdyListByGzfl (gzfl) {
      this.currGzfl = gzfl
      mySessionStorage.setItem("gzfl-item", this.currGzfl)
      return this.queryGzdyList()
    },
    async queryGzdyList () {
      if (!this.currGzfl.gzflbm) {
        return
      }
      this.gzdyList = await this.$api.queryGzdyListByGzflbm({
        gzflbm: this.currGzfl.gzflbm,
        sfzkzj: this.sfzkzj ? 'Y' : 'N',
        sfqy: this.sfqy,
      })
    },
    async delGzdy (gzdy) {
      try {
        let errArr = []
        if (Array.isArray(gzdy)) {
          for (let gzdyElement of gzdy) {
            try {
              await this.$api.deleteGzdy({ gzbm: gzdyElement.gzbm })
            } catch (e) {
              errArr.push(e.message)
            }
          }
        } else {
          await this.$api.deleteGzdy({ gzbm: gzdy.gzbm })
        }
        if (errArr.length) {
          this.$message({ message: `部分删除失败：${errArr.join(",")}`, type: 'warning' })
        } else {
          this.$message({ message: "删除成功", type: 'success' })
        }
      } catch (e) {
        this.$message({ message: e.message, type: 'error' })
      }
      this.queryGzdyList()
    },
    async setGzdyQyzt (gzdy) {
      try {
        const pam = { gzbm: gzdy.gzbm, sfqy: 'Y' }
        if (gzdy.sfqy === 'Y') pam.sfqy = "N"

        await this.$api.setGzdyQyzt(pam)
        this.$message({ message: "设置状态成功", type: 'success' })
        this.queryGzdyList()

        if (this.searchGzVisible) {
          this.queryGzinfoListByGjz()
        }

      } catch (e) {
        this.$message({ message: e.message, type: 'error' })
      }
    },
    getZsValue (gzpz) {
      if (!gzpz) return ''
      let val = JSON.parse(gzpz)[this.zsItem.bm]
      switch (this.zsItem.lx) {
        case "radio-button":
        case "select":
          let ii = this.zsItem.options.find(item => item.value == val)
          return ii ? ii.label : val
      }
      return val;
    },
    async designGz (gzdy) {
      mySessionStorage.setItem("gzdy-item", gzdy)
      this.$router.push(`/design`)
    },
    copySelectedGz () {
      let selection = this.$refs.gzTable.selection
      this.selectedGzbmList = selection.map(item => item.gzbm)
    },
    deleteSelectedGz () {
      let selection = this.$refs.gzTable.selection
      this.preDel(this.delGzdy, selection, `即将删除${selection.length}条规则，删除将不可恢复，是否删除？`)
    },
    editGzdy (gzdy) {
      if (!gzdy) {
        let gzfl = mySessionStorage.getItem("gzfl-item")
        gzdy = {
          gzbm: '',
          gzmc: '',
          gzms: '',
          gzpz: {},
          gzflbm: gzfl.gzflbm,
        }
        for (const xmpzElement of this.xmItem.xmpz.items) {
          gzdy.gzpz[xmpzElement.bm] = xmpzElement.mrz
        }
      } else {
        gzdy = {
          ...gzdy,
          gzpz: JSON.parse(gzdy.gzpz || '{}')
        }
      }
      for (let gzpzKey in gzdy.gzpz) {
        let pzItem = this.xmItem.xmpz.items.find(item => item.bm === gzpzKey)
        if (!pzItem) {
          delete gzdy.gzpz[gzpzKey]
        }
      }
      this.gzdyForm = gzdy
      this.editGzdyVisible = true
    },
    copyGz (gzdy) {
      this.selectedGzbmList = [gzdy.gzbm]
    },
    copyGzToGzfl (gzbm, gzflbm) {
      return this.$api.copyGz({ gzflbm: gzflbm, gzbm: gzbm })
    },
    async handleCopyGzBtnClick (isConfirm) {
      if (isConfirm) {
        try {
          for (let selectGzflKey in this.selectGzfl) {
            if (this.selectGzfl[selectGzflKey]) {
              for (let selectedGzbmListElement of this.selectedGzbmList) {
                await this.copyGzToGzfl(selectedGzbmListElement, selectGzflKey)
              }
            }
          }
        } catch (e) {
          return this.$message({ message: e.message, type: 'error' })
        }
        this.queryGzdyList()
        this.$message({ message: '规则复制完成', type: 'success' })
      }
      // this.selectGzflbm = null
      this.selectedGzbmList = []
    }
  }
}
</script>
<style lang="scss" scoped>
.search-inputbox {
  display: flex;

  .search-input {
    flex: 1;
    display: flex;

    .search-item {
      display: flex;
      align-items: center;
      margin-right: 10px;
      flex: 1;

      .label {
        width: 80px;
        text-align: center;
        box-sizing: border-box;

        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }
    }

  }
}
</style>
